<?php

/*
 * 2021/7/16
 * 14:14
 * User: 2650332702@qq.com
 */
namespace App\Api\Services;


use App\Api\Models\BlackIp;

class BlackWhite
{
    /**
     * 安全IP检测，支持IP段检测
     * @param string $ip 要检测的IP
     * @param string|array $ips  黑名单IP
     * @return array|boolean true 在黑名单中，否则不在
     */
    public function isSafeIp($ip="",$ips=""){
        if(!$ip) $ip = $this->getClientIp();  //获取客户端IP
        $ips = BlackIp::Everything();
        foreach ($ips as &$v){
            $array_ips[] = $v['black_ip'];
        }
        if(in_array($ip, $array_ips)){
            return false;
        }else{
            return true;
        }
    }


    /**
     * 获取客户端IP地址
     * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
     * @param boolean $adv 是否进行高级模式获取（有可能被伪装）
     * @return mixed
     */
    static public function getClientIp($type = 0,$adv=false) {
        $type       =  $type ? 1 : 0;
        static $ip  =   NULL;
        if ($ip !== NULL) return $ip[$type];
        if($adv){
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                $pos    =   array_search('unknown',$arr);
                if(false !== $pos) unset($arr[$pos]);
                $ip     =   trim($arr[0]);
            }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $ip     =   $_SERVER['HTTP_CLIENT_IP'];
            }elseif (isset($_SERVER['REMOTE_ADDR'])) {
                $ip     =   $_SERVER['REMOTE_ADDR'];
            }
        }elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip     =   $_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $long = sprintf("%u",ip2long($ip));
        $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
        return $ip[$type];
    }
}
